package cn.sell.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 允许跨域
 * 解决浏览器端如下报错：
 * <br>Access to XMLHttpRequest at 'http://localhost:8081/Ass/login'
 * <br>from origin 'http://localhost:8080' has been blocked by CORS policy:
 * <br>Response to preflight request doesn't pass access control check:
 * <br>No 'Access-Control-Allow-Origin' header is present on the requested resource.
 * <p>CORS支持跨域配置不生效且报的比上面的少了一行是因为路径错误（例如下面的少了Ass）
 * <br>Access to XMLHttpRequest at 'http://localhost:8081/list'
 * <br>from origin 'http://localhost:8080' has been blocked by CORS policy:
 * <br>No 'Access-Control-Allow-Origin' header is present on the requested resource.
 */
@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration configuration = new CorsConfiguration();
        // 是否允许请求带cookie
        configuration.setAllowCredentials(true);
        // 允许访问的客户端域名
        configuration.addAllowedOrigin("*");
        // 允许服务端访问的客户端请求头
        configuration.addAllowedHeader("*");
        // 允许访问的方法名,GET POST等
        configuration.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", configuration);
        return new CorsFilter(source);
    }
}